package com.qfedu.controller;


import com.github.wxpay.sdk.WXPay;
import com.qfedu.fmmall.service.job.MyPayConfig;
import com.qfedu.fmmall.entity.Orders;
import com.qfedu.fmmall.service.OrderService;
import com.qfedu.fmmall.vo.ResultStatus;
import com.qfedu.fmmall.vo.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("orders")
@CrossOrigin
@Api(tags = "订单管理",value = "订单数据的基本操作")
public class OrderController {


    @Autowired
    private OrderService orderService;

    @PostMapping("/add")
    public ResultVo addOrders(String cids, @RequestBody Orders orders){
        ResultVo resultVo = null;
        try {
            Map<String, String> orderInfo = orderService.addOrder(cids, orders);
            String orderId = orderInfo.get("orderId");
            if(orderId != null){
                //设置当前订单信息
                HashMap<String,String> data = new HashMap<>();
                data.put("body",orderInfo.get("productNames")); //商品描述
                data.put("out_trade_no",orderId);//使用当前用户订单的编号作为当前支付交易的交易号
                data.put("fee_type","CNY");//支付币中   人民币
                data.put("taotal_fee", orders.getActualAmount()*100+"");
                data.put("trade_type","NATIVE");//交易类型
                data.put("notify_url","pay/callback");//设置支付成功时回调方法

                //发送请求，获取响应
                //微信支付：申请支付链接
                WXPay wxPay = new WXPay(new MyPayConfig());
                Map<String,String> resq = wxPay.unifiedOrder(data);
                orderInfo.put("payUrl",resq.get("code_url"));

                resultVo = new ResultVo(ResultStatus.OK,"提交订单成功",orderInfo);
            }else{
                resultVo = new ResultVo(ResultStatus.NO,"订单提交失败",null);
            }

        }catch (Exception e){
            e.printStackTrace();
            resultVo = new ResultVo(ResultStatus.NO,"订单提交失败",null);
        }
        return resultVo;
    }


    @ApiOperation("查询用户订单")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String",name="userId",value = "用户id",required = true),
            @ApiImplicitParam(dataType = "String",name="status",value = "订单状态",required = false),
            @ApiImplicitParam(dataType = "int",name = "pageNum",value="当前页码",required = true),
            @ApiImplicitParam(dataType = "int",name="limit",value = "页面显示长度",required = true)
    })
    public ResultVo orderList(@RequestHeader("token")String token,
            String userId,String status,int pageNum,int limit){
        return  orderService.OrderList(userId, status, pageNum, limit);
    }
}
